package com.cloud.gateway.config;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 测试过滤器的pre和post用法
 *
 * @author H
 */
@Component
@Slf4j
public class ChainGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //uri模板变量获取
                Map<String, String> map = ServerWebExchangeUtils.getUriTemplateVariables(exchange);
                String fl = map.get("fl");
                log.info("fl=={}", fl);
                log.info("过滤链开始==" + config.getName() + "==" + config.getValue());
                exchange.getAttributes().put("startTime", System.currentTimeMillis());
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    log.info("过滤链结束");
                    long startTime = (long) exchange.getAttributes().get("startTime");
                    log.info("过滤链执行时间=={}", System.currentTimeMillis() - startTime);
                }));
            }
        };
    }
}
